/*
 * Copyright 2005-2010 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.xml.stream;

import java.util.List;
import java.util.NoSuchElementException;
import javax.xml.stream.events.XMLEvent;

import org.springframework.util.Assert;

/**
 * @author Arjen Poutsma
 */
public class ListBasedXMLEventReader extends AbstractXMLEventReader {

	private final XMLEvent[] events;

	private int cursor = 0;

	public ListBasedXMLEventReader() {
		this.events = new XMLEvent[0];
	}

	public ListBasedXMLEventReader(XMLEvent event) {
		if (event != null) {
			this.events = new XMLEvent[]{event};
		}
		else {
			this.events = new XMLEvent[0];
		}
	}

	public ListBasedXMLEventReader(XMLEvent... events) {
		Assert.notNull(events, "'events' must not be null");
		this.events = events;
	}

	public ListBasedXMLEventReader(List<XMLEvent> events) {
		Assert.notNull(events, "'events' must not be null");
		this.events = events.toArray(new XMLEvent[events.size()]);
	}

	public boolean hasNext() {
		Assert.notNull(events, "'events' must not be null");
		return cursor != events.length;
	}

	public XMLEvent nextEvent() {
		if (cursor < events.length) {
			return events[cursor++];
		}
		else {
			throw new NoSuchElementException();
		}
	}

	public XMLEvent peek() {
		if (cursor < events.length) {
			return events[cursor];
		}
		else {
			return null;
		}
	}
}
